﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverCheques.localSilverService;
using Cheque=SilverCheques.SilverService.Cheque;
using SilverChequeServiceClient=SilverCheques.SilverService.SilverChequeServiceClient;

namespace SilverCheques
{
    public partial class MainPage : UserControl
    {
        SilverService.SilverChequeServiceClient svc = new SilverChequeServiceClient();

        public MainPage()
        {
            InitializeComponent();
            btnSaveTextFile.Click +=new RoutedEventHandler(btnMakeText_Click);
            Loaded += new RoutedEventHandler(MainPage_Loaded);
            svc.GetChequesCompleted += new EventHandler<SilverCheques.SilverService.GetChequesCompletedEventArgs>(svc_GetChequesCompleted);
            dfsCustomerName.LostFocus +=new RoutedEventHandler(dfsCustomerName_LostFocus);
            dfsCustomerAddress1.LostFocus += new RoutedEventHandler(dfsCustomerAddress1_LostFocus);
            dfsCustomerAddress2.LostFocus += new RoutedEventHandler(dfsCustomerAddress2_LostFocus);
            dfsCustomerAddress3.LostFocus += new RoutedEventHandler(dfsCustomerAddress3_LostFocus);
            dfsCustomerAddress4.LostFocus += new RoutedEventHandler(dfsCustomerAddress4_LostFocus);
            dfsBankName.LostFocus += new RoutedEventHandler(dfsBankName_LostFocus);
            dfsBankAddress1.LostFocus += new RoutedEventHandler(dfsBankAddress1_LostFocus);
            dfsBankAddress2.LostFocus += new RoutedEventHandler(dfsBankAddress2_LostFocus);
            dfsBankAddress3.LostFocus += new RoutedEventHandler(dfsBankAddress3_LostFocus);
            lstCustomers.SelectionChanged +=new SelectionChangedEventHandler(lstCustomers_SelectionChanged);
            btnAddNew.Click += new RoutedEventHandler(btnAddNew_Click);
            btnSaveCheque.Click += new RoutedEventHandler(btnSaveCheque_Click);
            svc.InsertChequeCompleted += new EventHandler<SilverCheques.SilverService.InsertChequeCompletedEventArgs>(svc_InsertChequeCompleted);
            svc.UpdateChequeCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(svc_UpdateChequeCompleted);
            svc.DeleteChequeCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(svc_DeleteChequeCompleted);
            btnDelete.Click += new RoutedEventHandler(btnDelete_Click);
        }

        void svc_DeleteChequeCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            BeginStoryBoard("SaveChequeEnd");
        }

        void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            var cheque = (Cheque)this.DataContext;
            if (cheque != null && cheque.Id > 0) 
            {
                svc.DeleteChequeAsync(cheque.Id);
                BeginStoryBoard("SaveChequeBegin");
                svc.GetChequesAsync();
            }
        }

        void svc_UpdateChequeCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            BeginStoryBoard("SaveChequeEnd");
        }

        void svc_InsertChequeCompleted(object sender, SilverCheques.SilverService.InsertChequeCompletedEventArgs e)
        {
            BeginStoryBoard("SaveChequeEnd");
        }

        void btnSaveCheque_Click(object sender, RoutedEventArgs e)
        {
            var cheque =  (Cheque) this.DataContext;
            if (cheque.Id == 0) //insert new Check
            {
                BeginStoryBoard("SaveChequeBegin");
                svc.InsertChequeAsync(cheque);
                svc.GetChequesAsync();
            }
            else // Update existing check
            {
                BeginStoryBoard("SaveChequeBegin");
                svc.UpdateChequeAsync(cheque);
                svc.GetChequesAsync();
            }

        }

        void btnAddNew_Click(object sender, RoutedEventArgs e)
        {
            this.DataContext = new Cheque();
            BeginStoryBoard("AddNewCheque");
        }


        void dfsBankAddress3_LostFocus(object sender, RoutedEventArgs e)
        {
            ReplaceComma(dfsBankAddress3);
        }

        void dfsBankAddress2_LostFocus(object sender, RoutedEventArgs e)
        {
            ReplaceComma(dfsBankAddress2);
        }

        void dfsBankAddress1_LostFocus(object sender, RoutedEventArgs e)
        {
            ReplaceComma(dfsBankAddress1);
        }

        void dfsBankName_LostFocus(object sender, RoutedEventArgs e)
        {
            ReplaceComma(dfsBankName);
        }

        void dfsCustomerAddress4_LostFocus(object sender, RoutedEventArgs e)
        {
            ReplaceComma(dfsCustomerAddress4);
        }

        void dfsCustomerAddress3_LostFocus(object sender, RoutedEventArgs e)
        {
            ReplaceComma(dfsCustomerAddress3);
        }

        void dfsCustomerAddress2_LostFocus(object sender, RoutedEventArgs e)
        {
            ReplaceComma(dfsCustomerAddress2);
        }

        void dfsCustomerAddress1_LostFocus(object sender, RoutedEventArgs e)
        {
            ReplaceComma(dfsCustomerAddress1);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            //localSilverService.SilverChequeServiceClient svc = new SilverChequeServiceClient();
            //svc.GetChequesCompleted += new EventHandler<GetChequesCompletedEventArgs>(svc_GetChequesCompleted);

            
            svc.GetChequesAsync();

            for (int i = 1; i <= 15000; i++)
            {
                dfnSerialFrom.Items.Add(i);
                dfnSerialTo.Items.Add(i);
            }

        }

        void svc_GetChequesCompleted(object sender, SilverCheques.SilverService.GetChequesCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                lstCustomers.DataContext = e.Result;
                lstCustomers.ItemsSource = e.Result;
                lstCustomers.DisplayMemberPath = "CustomerName";
                lstCustomers.SelectedItem = lstCustomers.Items[0];
            }
            else
            {
                txtError.Text = e.Error.Message;
            }
        }

        void svc_GetChequesCompleted(object sender, GetChequesCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                this.DataContext = e.Result;
                lstCustomers.ItemsSource = e.Result;
                lstCustomers.DisplayMemberPath = "CustomerName";
            }
            else
            {
                txtError.Text = e.Error.Message;
            }

        }

        private void btnMakeText_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {

                const string fileName = "CHEQUEMERGE";
                //CreateTextFile(fileName + ".txt");
                SaveTextFile(fileName + ".txt");
                DownloadDocFile(fileName + ".doc");
                btnSaveDocFile.IsEnabled = true;
                btnSaveTextFile.IsEnabled = false;
            }
            catch (Exception exception )
            {

                txtError.Text = exception.Message;
            }

        }

        private void DownloadDocFile(string fileName)
        {
            var client = new WebClient();
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(Client_OpenReadCompleted);
            client.OpenReadAsync(new Uri("http://bpwe.net/C/doc/" + fileName));
            //Client.OpenReadAsync(new Uri("http://localhost:29890/doc/" + fileName));
        }

        private void SaveTextFile(string fileName)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.DefaultExt = ".txt";
            saveFileDialog.Filter = "Text Files (*.txt)|*.txt";
            bool? dialogresult = saveFileDialog.ShowDialog();
            if ((bool)dialogresult)
            {
               Stream fs = (Stream)saveFileDialog.OpenFile();
               CreateTextFile(fs);
            }

        }

        private void CreateTextFile(Stream fs)
        {
            var selectedCheque = (Cheque)this.DataContext;
            if (selectedCheque == null)
            {
                txtError.Text = "No Selected Cheques";
                return;
            }
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}",
                    "BankName1",
                    "BankAddress1",
                    "BankAddress2",
                    "BankAddress3",
                    "CustomerName",
                    "CustomerAddress1",
                    "CustomerAddress2",
                    "CustomerAddress3",
                    "CustomerAddress4",
                    "RoutingNumber",
                    "AccountNumber",
                    "SerialNumber"));

                for (int i = (int.Parse(dfnSerialFrom.Value.ToString())); i <= int.Parse(dfnSerialTo.Value.ToString()); i++)
                {

                    sw.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11:D5}",
                        selectedCheque.BankName,
                            selectedCheque.BankAddress1,
                            selectedCheque.BankAddress2,
                            selectedCheque.BankAddress3,
                            selectedCheque.CustomerName,
                            selectedCheque.CustomerAddress1,
                            selectedCheque.CustomerAddress2,
                            selectedCheque.CustomerAddress3,
                            selectedCheque.CustomerAddress4,
                            selectedCheque.RoutingNumber,
                            selectedCheque.AccountNumber,
                            i));
                }

                sw.Close();
            }
        }

        private void CreateTextFile(string fileName)
        {

        }

        void Client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (
                        IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("Cheques.doc", FileMode.Create,
                                                                                       isf))
                    {
                        using (BinaryWriter sw = new BinaryWriter(isfs))
                        {

                            byte[] bytes = new byte[e.Result.Length];
                            e.Result.Read(bytes, 0, (int) e.Result.Length);
                            sw.Write(bytes);
                            sw.Close();


                        }
                    }
                }
            }
            else //report error
            {
                txtError.Text = e.Error.Message;
            }
        }


        private void btn1_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                SaveDocFile();
            }
            catch (Exception exception)
            {

                txtError.Text = exception.Message;
            }
            
        }

        private void SaveDocFile()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("Cheques.doc", FileMode.Open, isf))
                {
                    using (BinaryReader sr = new BinaryReader(isfs))
                    {

                        byte[] bytes = sr.ReadBytes((int) isfs.Length);
                        sr.Close();
                        saveFileDialog.DefaultExt = ".doc";
                        saveFileDialog.Filter = "Document Files (*.doc)|*.doc";
                        bool dialogresult = (bool)saveFileDialog.ShowDialog();

                        if (dialogresult)
                        {
                            using (Stream fs = (Stream)saveFileDialog.OpenFile())
                            {
                                fs.Write(bytes, 0, bytes.Length);
                                fs.Close();
                            }
                        } 
                    }
                }


            }
            btnSaveDocFile.IsEnabled = false;
            btnSaveTextFile.IsEnabled = true;
        }

        private void btnSaveTextFile_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {

                using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("Cheques.txt", FileMode.Open, isf)
                    )
                {
                    using (BinaryReader sr = new BinaryReader(isfs))
                    {

                        saveFileDialog.DefaultExt = ".txt";
                        saveFileDialog.Filter = "Text Files|*.txt";
                        bool? dialogResult = saveFileDialog.ShowDialog();

                        if (dialogResult == true)
                        {
                            byte[] bytes = sr.ReadBytes((int) isfs.Length);
                            sr.Close();
                            using (Stream fs = (Stream) saveFileDialog.OpenFile())
                            {
                                fs.Write(bytes, 0, bytes.Length);
                                fs.Close();
                            }
                        }
                    }
                }
            }
        }

        private void dfsCustomerName_LostFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            ReplaceComma(dfsCustomerName);
        }

        private void ReplaceComma(TextBox txtbox)
        {
            txtbox.Text = txtbox.Text.Replace(',', ';');
        }

        private void lstCustomers_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            try
            {
                PopulateSelectedCheque(e);
                AnimateSelectCheque(new object());

            }
            catch (Exception exception )
            {

                txtError.Text = exception.Message;
            }

        }

        private void PopulateSelectedCheque(SelectionChangedEventArgs e)
        {
            if (e.AddedItems != null && e.AddedItems.Count > 0)
            {
                var selectedCheque = (SilverService.Cheque) e.AddedItems[0];
                this.DataContext = selectedCheque;
            }
        }

        private void PopulateControls(Cheque selectedCheque)
        {
            dfsCustomerName.Text = selectedCheque.CustomerName;
            dfsCustomerAddress1.Text = selectedCheque.CustomerAddress1;
            dfsCustomerAddress2.Text = selectedCheque.CustomerAddress2;
            dfsCustomerAddress3.Text = selectedCheque.CustomerAddress3;
            dfsCustomerAddress4.Text = selectedCheque.CustomerAddress4;
            dfsAccountNumber.Text = selectedCheque.AccountNumber;


            dfsBankName.Text = selectedCheque.BankName;
            dfsBankAddress1.Text = selectedCheque.BankAddress1;
            dfsBankAddress2.Text = selectedCheque.BankAddress2;
            dfsBankAddress3.Text = selectedCheque.BankAddress3;
            dfsRoutingNumber.Text = selectedCheque.RoutingNumber;
        }

        private void AnimateSelectCheque(object state)
        {
            Storyboard storyboard = (Storyboard) Resources["ShowSelectedCheque"];
            storyboard.Begin();
        }

        private void BeginStoryBoard(string  storyboardName)
        {
            Storyboard storyboard = (Storyboard)Resources[storyboardName];
            storyboard.Begin();
        }

        private void BackgroundAnimateSelectCheque()
        {
            ThreadPool.QueueUserWorkItem(AnimateSelectCheque, new object());
        }

        private void btnOpenDocument_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog {Filter = "Document Files|*.doc"};
            openFileDialog.ShowDialog();
            

        }

        private void btnHelp_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	HelpFont helpFont = new HelpFont();
            helpFont.Show();
        }
    }
}
